package com.cheyunkeji.er.activity.auction;

import android.content.Intent;
import android.os.Looper;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.TextView;

import com.cheyun.netsalev3.R;
import com.cheyunkeji.er.Constants;
import com.cheyunkeji.er.adapter.citymodel.CityAdapter;
import com.cheyunkeji.er.adapter.citymodel.CitySortAdapter;
import com.cheyunkeji.er.base.BaseActivity;
import com.cheyunkeji.er.model.CitySortModel;
import com.cheyunkeji.er.utils.PinyinComparator;
import com.cheyunkeji.er.utils.PinyinUtils;
import com.cheyunkeji.er.view.TopBar;
import com.cheyunkeji.er.view.cityview.EditTextWithDel;
import com.cheyunkeji.er.view.cityview.SideBar;
import com.tencent.map.geolocation.TencentLocation;
import com.tencent.map.geolocation.TencentLocationListener;
import com.tencent.map.geolocation.TencentLocationManager;
import com.tencent.map.geolocation.TencentLocationRequest;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class CitySelectActivity extends BaseActivity implements TencentLocationListener {

    @BindView(R.id.v_topbar)
    TopBar vTopbar;
    @BindView(R.id.et_search)
    EditTextWithDel mEtCityName;
    @BindView(R.id.country_lvcountry)
    ListView sortListView;
    @BindView(R.id.dialog)
    TextView dialog;
    @BindView(R.id.sidrbar)
    SideBar sideBar;
    private TextView tvLocation;

    private CitySortAdapter adapter;
    private List<CitySortModel> SourceDateList;

    private TencentLocationManager locationManager;
    private TencentLocationRequest locationRequest;


    private String CURRENT_LOCATE_ADDRESS;

    @Override
    protected void init() {
        setContentView(R.layout.er_activity_city_select);
        ButterKnife.bind(this);
        initLocation();
    }

    private void initLocation() {
        // 用于访问腾讯定位服务的类, 周期性向客户端提供位置更新
        locationManager = TencentLocationManager.getInstance(this);
        locationManager.requestSingleFreshLocation(null, this, Looper.getMainLooper());
        // 创建定位请求
        locationRequest = TencentLocationRequest.create();
        // 设置定位周期（位置监听器回调周期）为3s
        locationRequest.setInterval(3000);
    }

    @Override
    public void onLocationChanged(TencentLocation tencentLocation, int i, String s) {
        if (TencentLocation.ERROR_OK == i) {
            // 定位成功
            if (tencentLocation != null) {
                String city = tencentLocation.getCity();
                tvLocation.setEnabled(true);
                tvLocation.setText(city);
                CURRENT_LOCATE_ADDRESS = tencentLocation.getProvince() + tencentLocation.getCity();
            }
        } else {
            // 定位失败
            tvLocation.setText("定位失败");
        }
    }

    @Override
    public void onStatusUpdate(String s, int i, String s1) {}

    @Override
    protected void initView() {
        vTopbar.setTitle("请选择城市");
        vTopbar.setLeftBack();
        sideBar.setTextView(dialog);
        initEvents();
    }

    @Override
    protected void initData() {
        setAdapter();
    }


    private void setAdapter() {
        SourceDateList = filledData(getResources().getStringArray(R.array.provinces));
        Collections.sort(SourceDateList, new PinyinComparator());
        adapter = new CitySortAdapter(this, SourceDateList);
        sortListView.addHeaderView(initHeadView());
        sortListView.setAdapter(adapter);
    }

    private void initEvents() {
        //设置右侧触摸监听
        sideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {
            @Override
            public void onTouchingLetterChanged(String s) {
                //该字母首次出现的位置
                int position = adapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    sortListView.setSelection(position + 1);
                }
            }
        });

        //ListView的点击事件
        sortListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

                if (position != 0)
                    returnDataBySetResult("city_name", ((CitySortModel) adapter.getItem(position - 1)).getName());

//                Toast.makeText(getApplication(), ((CitySortModel) adapter.getItem(position-1)).getName(), Toast.LENGTH_SHORT).show();
            }
        });

        //根据输入框输入值的改变来过滤搜索
        mEtCityName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
                filterData(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    /**
     * 返回数据（城市名称）给上一个页面
     */
    private void returnDataBySetResult(String name, String value) {
        Intent intent = new Intent();
        intent.putExtra(name, value);
        setResult(Constants.RESULT_CODE_OK, intent);
        finish();
    }

    private View initHeadView() {
        View headView = getLayoutInflater().inflate(R.layout.er_headview, null);
        tvLocation = (TextView) headView.findViewById(R.id.tv_location);
        final GridView mGvCity = (GridView) headView.findViewById(R.id.gv_hot_city);
        String[] datas = getResources().getStringArray(R.array.city);
        ArrayList<String> cityList = new ArrayList<>();
        for (int i = 0; i < datas.length; i++) {
            cityList.add(datas[i]);
        }
        CityAdapter adapter = new CityAdapter(getApplicationContext(), R.layout.er_gridview_item, cityList);
        mGvCity.setAdapter(adapter);
        mGvCity.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//                Toast.makeText(CitySelectActivity.this, adapterView.getAdapter().getItem(i)+"", Toast.LENGTH_SHORT).show();
//                Log.e(MainActivity.class.getSimpleName(), "GridItem Clicked!");
                returnDataBySetResult("city_name", adapterView.getAdapter().getItem(i) + "市");
            }
        });
        tvLocation.setOnClickListener(this);
        return headView;
    }

    /**
     * 根据输入框中的值来过滤数据并更新ListView
     *
     * @param filterStr
     */
    private void filterData(String filterStr) {
        List<CitySortModel> mSortList = new ArrayList<>();
        if (TextUtils.isEmpty(filterStr)) {
            mSortList = SourceDateList;
        } else {
            mSortList.clear();
            for (CitySortModel sortModel : SourceDateList) {
                String name = sortModel.getName();
                if (name.toUpperCase().indexOf(filterStr.toString().toUpperCase()) != -1 || PinyinUtils.getPingYin(name).toUpperCase().startsWith(filterStr.toString().toUpperCase())) {
                    mSortList.add(sortModel);
                }
            }
        }
        // 根据a-z进行排序
        Collections.sort(mSortList, new PinyinComparator());
        adapter.updateListView(mSortList);
    }

    private List<CitySortModel> filledData(String[] date) {
        List<CitySortModel> mSortList = new ArrayList<>();
        ArrayList<String> indexString = new ArrayList<>();

        for (int i = 0; i < date.length; i++) {
            CitySortModel sortModel = new CitySortModel();
            sortModel.setName(date[i]);
            String pinyin = PinyinUtils.getPingYin(date[i]);
            String sortString = pinyin.substring(0, 1).toUpperCase();
            if (sortString.matches("[A-Z]")) {
                sortModel.setInitial(sortString.toUpperCase());
                if (!indexString.contains(sortString)) {
                    indexString.add(sortString);
                }
            }
            mSortList.add(sortModel);
        }
        Collections.sort(indexString);
        sideBar.setIndexText(indexString);
        return mSortList;
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);

        switch (v.getId()) {
            case R.id.tv_location:
                if (CURRENT_LOCATE_ADDRESS != null || !TextUtils.isEmpty(CURRENT_LOCATE_ADDRESS)) {
                    returnDataBySetResult("city_name", CURRENT_LOCATE_ADDRESS);
                }
                break;
//            case value2:
//
//                break;
//            case value3:
//
//                break;
            default:
                break;
        }
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        destroyLocation();
    }

    private void destroyLocation() {
        if (locationManager != null) {
            locationManager.removeUpdates(this);
        }
    }
}
